package com.ruoyi.project.system.reservation.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.coachPlan.domain.CoachPlan;
import com.ruoyi.project.system.coachPlan.service.ICoachPlanService;
import com.ruoyi.project.system.reservation.domain.Reservation;
import com.ruoyi.project.system.reservation.service.IReservationService;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.system.userCoachBind.domain.UserCoachBind;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.mchange.lang.ShortUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;

/**
 * 预约记录信息操作处理
 * 
 * @author zhangshilin
 * @date 2019-06-26
 */
@Controller
@RequestMapping("/system/reservation")
public class ReservationController extends BaseController
{
    private String prefix = "system/reservation";
	
	@Autowired
	private IReservationService reservationService;
	@Autowired
	private IUserService userService;
	@Autowired
	private ICoachPlanService coachPlanService;
	@Autowired
	private IRoleService roleService;
	
	@RequiresPermissions("system:reservation:view")
	@GetMapping()
	public String reservation()
	{
	    return prefix + "/reservation";
	}
	
	/**
	 * 学员预约界面
	 * (因为李想要教练页面单独可预约几人，而学员页面只显示可预约，所以加了教练预约界面，如果修改学员页面，相应也要修改教练页面)
	 * @return
	 */
	@RequiresPermissions("system:traineeReserve:view")
	@GetMapping("/traineeReserve")
	public String traineeReserve(String phone,ModelMap map)
	{
		map.addAttribute("phone", phone);
		if(phone!=null) {
			User user = userService.selectUserByPhoneNumber(phone);
			map.addAttribute("name", user.getUserName());
		}
	    return prefix + "/traineeReserve";
	}
	
	/**
	 * 教练预约界面
	 * @return
	 */
	@RequiresPermissions("system:traineeReserve:view")
	@GetMapping("/coachReserve")
	public String coachReserve(String phone,ModelMap map)
	{
		map.addAttribute("phone", phone);
		if(phone!=null) {
			User user = userService.selectUserByPhoneNumber(phone);
			map.addAttribute("name", user.getUserName());
		}
	    return prefix + "/coachReserve";
	}
	
	/**
	 * 学员预约界面(手机版)
	 * @return
	 */
	@RequiresPermissions("system:traineeReserve:view")
	@GetMapping("/traineeReserveByPhone")
	public String traineeReserveByPhone(String phone,ModelMap map)
	{
		map.addAttribute("phone", phone);
		User user = userService.selectUserByPhoneNumber(phone);
		map.addAttribute("user", user);
	    return prefix + "/traineeReserveByPhone";
	}
	
	/**
	 * 查询学员当前可预约的教练
	 * 
	 */
	@RequiresPermissions("system:traineeReserve:view")
	@PostMapping("/traineeReserveList")
	@ResponseBody
	public Object traineeReserveList(String beginTime,String phone)
	{
		//当前登录用户
		User currentUser = getSysUser();
		
		//如果phone为空，表示从{预约教练}进来，是学员主动预约行为，取当前登录用户的phone
		//如果phone有值，表示从{我的学员-预约教练}进来，是教练帮助学员预约,取传进来的phone值
		if("".equals(phone)||phone==null) {
			phone = currentUser.getPhonenumber();
		}
		//学员
		User user = userService.selectUserByPhoneNumber(phone);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfhh = new SimpleDateFormat("HH");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			//当前选择的时间
			if("".equals(beginTime)||beginTime==null) {
				beginTime = sdf.format(new Date());
			}
			Date nowdate = sdf.parse(beginTime);//选择时间
			
			List<Map<String, Object>> resList = new ArrayList<>();
			List<User> coachList = null;
			
			//查出学员绑定的教练
			List<UserCoachBind> userCoachBinds = userService.queryByuserId(user.getUserId());
			if(userCoachBinds.size()>1) {
				return AjaxResult.error("当前学员绑定了多个教练，请联系管理员确认！");
			}else if(userCoachBinds.size()==0) {
				//如果是管理员就不提示
				User isadmin = userService.selectIsRole(user.getUserId(), "管理员");
				if(isadmin==null) {
					return AjaxResult.error("当前学员未绑定教练，请联系管理员确认！");
				}
				
			}
			User coach = userService.selectUserById(userCoachBinds.get(0).getCoachid().longValue());
			
			/*// 获取当前的用户信息
			User currentUser = ShiroUtils.getSysUser();
			User Trainee = userService.selectIsRole(currentUser.getUserId(), "学员");
			if(Trainee!=null) {
				//如果是学员，则只查当前学员可预约的教练。
				coachList = userService.selectByGroupCoach(Trainee.getDrivingLicenseType(), Trainee.getSubject());
				if(coachList.size()<=0) {
					return AjaxResult.error("当前无可预约教练");
				}
			}else {
				coachList = userService.selectGroupCoach();
				if(coachList.size()<=0) {
					return AjaxResult.error("当前无可预约教练");
				}
			}*/
				
				//查询出选择时间的可预约教练计划
				/*CoachPlan coachPlan = new CoachPlan();
				coachPlan.setCoachPhone(coach.getPhonenumber());
				coachPlan.setNowDate(beginTime);
				coachPlan.setIsDisable("1");//可用状态
*/				
				String [] nowdates = new String[10];
				nowdates[0] = beginTime;
				//利用Calendar 实现 Date日期+1天  
				Calendar c = Calendar.getInstance(); 
				for (int i = 1; i < 10; i++) {
		            c.setTime(nowdate);  
		            c.add(Calendar.DAY_OF_MONTH, i);//+i天
		             
		            Date sDate = c.getTime();
		            nowdates[i] = sdf.format(sDate);
				}
				//查询这个教练的所有计划
				CoachPlan coachPlan = new CoachPlan();
				coachPlan.setCoachPhone(coach.getPhonenumber());
				coachPlan.setIsDisable("1");//可用状态
				List<CoachPlan> coachPlanList = coachPlanService.selectCoachPlanList(coachPlan);
				
				for (int j=0;j<nowdates.length;j++) {
					//取出相同的教练整合到一起
					Map<String, Object> coachMap = new HashMap<>();
	        		coachMap.put("coachName", coach.getUserName());
	        		//这里加上星期几显示
	        		String week = DateUtils.getWeekOfDate(sdf.parse(nowdates[j]));
	        		coachMap.put("date", nowdates[j]);
	        		coachMap.put("week", week);
	        		coachMap.put("coachPhone", coach.getPhonenumber());
	        		int time8=-1,time9=-1,time10=-1,time11=-1,time12=-1,time13=-1,time14=-1,time15=-1,time16=-1,time17=-1,time18=-1,time19 = -1;
	        		//显示默认的-1，页面上会显示--
	        		coachMap.put("time8", time8);
					coachMap.put("time9", time9);
					coachMap.put("time10", time10);
					coachMap.put("time11", time11);
					coachMap.put("time12", time12);
					coachMap.put("time13", time13);
					coachMap.put("time14", time14);
					coachMap.put("time15", time15);
					coachMap.put("time16", time16);
					coachMap.put("time17", time17);
					coachMap.put("time18", time18);
					coachMap.put("time19", time19);
					
					if(coachPlanList.size()>0) {
						//把所有得可预约数据整合到
						for (CoachPlan coachPlans : coachPlanList) {
							if(nowdates[j].equals(coachPlans.getNowDate()) && coachMap.get("coachPhone").equals(coachPlans.getCoachPhone())) {
								String time = sdfhh.format(coachPlans.getStatrtTime());
								String strDate = coachPlans.getNowDate()+" "+time + ":00:00";//预约的开始时间
								Date StatrtTime = simpleDateFormat.parse(strDate);
								//根据预约的开始时间查询有几个学员预约了
								Reservation reservation = new Reservation();
								reservation.setStatrtTime(StatrtTime);
								reservation.setCoachName(coachPlans.getCoachName());
								reservation.setIsDisable("1");
								List<Reservation> reservationList =  reservationService.selectReservationList(reservation);
								int reservationSize = reservationList.size();//当前教练此时刻已预约的学员数量
								int coachPlanSize = coachPlans.getSeatNumber().intValue();//当前教练的此时刻可预约的数量
								int num = coachPlanSize - reservationSize;
								
								//currentUser判断当前登录学员如果和已预约学员一致，就返回-2(已预约)---0是已约满，1，是可预约1人，-1是未排班
								for (Reservation reservationTeam : reservationList) {
									if(currentUser.getPhonenumber()!=null && reservationTeam.getUserPhone()!=null) {
										if(currentUser.getPhonenumber().equals(reservationTeam.getUserPhone())) {
											num = -2;
										}
									}
									
									
								}
								switch (time) {
								case "08":
	    							time8 = num;
	    							coachMap.put("time8", time8);
	    							break;
	    						case "09":
	    							time9 = num;
	    							coachMap.put("time9", time9);
	    							break;
	    						case "10":
	    							time10 = num;
	    							coachMap.put("time10", time10);
	    							break;
	    						case "11":
	    							time11 = num;
	    							coachMap.put("time11", time11);
	    							break;
	    						case "12":
	    							time12 = num;
	    							coachMap.put("time12", time12);
	    							break;
	    						case "13":
	    							time13 = num;
	    							coachMap.put("time13", time13);
	    							break;
	    						case "14":
	    							time14 = num;
	    							coachMap.put("time14", time14);
	    							break;
	    						case "15":
	    							time15 = num;
	    							coachMap.put("time15", time15);
	    							break;
	    						case "16":
	    							time16 = num;
	    							coachMap.put("time16", time16);
	    							break;
	    						case "17":
	    							time17 = num;
	    							coachMap.put("time17", time17);
	    							break;
	    						case "18":
	    							time18 = num;
	    							coachMap.put("time18", time18);
	    							break;
	    						case "19":
	    							time19 = num;
	    							coachMap.put("time19", time19);
	    							break;

	    						default:
	    							break;
	    						}
								
							}
						}
					}
					resList.add(coachMap);
				}
				return getDataTable(resList);
				
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}
	
	/**
	 * 查询预约记录列表
	 */
	@RequiresPermissions("system:reservation:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Reservation reservation)
	{
		// 获取当前的用户信息
		User currentUser = ShiroUtils.getSysUser();
		
		User coach = userService.selectIsRole(currentUser.getUserId(), "教练");
		User Trainee = userService.selectIsRole(currentUser.getUserId(), "学员");
		
		if(coach!=null) {
			//如果是教练
			reservation.setCoachPhone(coach.getPhonenumber());
		}else if(Trainee!=null) {
			//如果是学员
			reservation.setUserPhone(Trainee.getPhonenumber());
		}

		startPage();
        List<Reservation> list = reservationService.selectReservationList(reservation);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出预约记录列表
	 */
	@RequiresPermissions("system:reservation:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Reservation reservation)
    {
    	List<Reservation> list = reservationService.selectReservationList(reservation);
        ExcelUtil<Reservation> util = new ExcelUtil<Reservation>(Reservation.class);
        return util.exportExcel(list, "reservation");
    }
	
	/**
	 * 新增预约记录
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存预约记录
	 */
	@RequiresPermissions("system:reservation:add")
	@Log(title = "预约记录", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(@Param("coachName")String coachName,@Param("coachPhone")String coachPhone,
			@Param("date")Date date,@Param("timeValue")String timeValue,@Param("phone") String phone)
	{		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当前的用户信息
		User currentUser = null;
		if("".equals(phone)||phone==null) {
			currentUser = ShiroUtils.getSysUser();
		}else {
			currentUser = userService.selectUserByPhoneNumber(phone);
		}
		
		//当前时间
		Date now = new Date();
		if("".equals(coachName)&&"".equals(coachPhone)) {
			return AjaxResult.error("参数错误");
		}
		if("".equals(date)||date==null) {
			return AjaxResult.error("参数错误");
		}
		if("".equals(timeValue)||timeValue==null) {
			return AjaxResult.error("参数错误");
		}
		/*List<User> userList = userService.checkPhone(phone);
		if(userList.size()==0) {
			return AjaxResult.error("手机号不存在");
		}else if(userList.size()>1) {
			return AjaxResult.error("此手机号存在两个账号，请修改后操作");
		}*/
		//取出需要预约的用户信息
		//User user = userList.get(0);
		
		
		try {
			//转换成yyyy-MM-dd HH:mm:ss类型的时间，使用statrtTime接收
			timeValue = timeValue.replace("time", "");
			int addtime = Integer.parseInt(timeValue);
			//开始和结束时间
			long startTimeL = date.getTime()+addtime*60*60*1000;
			long endTimeL = date.getTime()+(addtime+1)*60*60*1000;
			Date statrtTime = new Date(startTimeL);
			Date endTime = new Date(endTimeL);
			//查询选择的教练信息
			User coachUser = userService.selectUserByPhoneNumber(coachPhone);
			if(coachUser==null) {
				return AjaxResult.error("教练手机号有误");
			}
			
			//查询相匹配的教练（coachName,coachPhone,statrtTime）验证是否还有可预约名额；
			//=======================
			//查询当前教练已预约的学员数量
			Reservation reservationVer = new Reservation();
			reservationVer.setStatrtTime(statrtTime);
			reservationVer.setCoachName(coachName);
			reservationVer.setIsDisable("1");
			List<Reservation> reservationList =  reservationService.selectReservationList(reservationVer);
			
			//判断当前学员是否已预约过
			if(reservationList.size()>0) {
				for (Reservation reservation : reservationList) {
					if(currentUser.getPhonenumber().equals(reservation.getUserPhone())) {
						return AjaxResult.error("请勿重复预约");
					}
				}
			}
			
			
			
			int reservationSize = reservationList.size();//当前教练此时刻已预约的学员数量
			
			//查询当前教练的可预约数量
			CoachPlan coachPlanVer = new CoachPlan();
			coachPlanVer.setStatrtTime(statrtTime);
			coachPlanVer.setCoachName(coachName);
			coachPlanVer.setCoachPhone(coachPhone);
			coachPlanVer.setIsDisable("1");
			List<CoachPlan> coachPlanList = coachPlanService.selectCoachPlanList(coachPlanVer);
			if(coachPlanList.size()<=0) {
				return AjaxResult.error("该教练没有当前没有预约计划");
			}
			CoachPlan coachPlan = coachPlanList.get(0);
			int coachPlanSize = coachPlan.getSeatNumber().intValue();//当前教练的此时刻可预约的数量
			
			int num = coachPlanSize - reservationSize;
			if(num<=0) {
				return AjaxResult.error("该教练当前时间已约满，请选择其他时间");
			}
			//=======================
			
			//记录存入预约表Reservation
			Reservation reservationAdd = new Reservation();
			reservationAdd.setCoachId(coachUser.getUserId().intValue());
			reservationAdd.setCoachName(coachName);//教练姓名
			reservationAdd.setCoachPhone(coachPhone);
			reservationAdd.setCreateBy(currentUser.getUserName());
			reservationAdd.setCreateTime(now);
			reservationAdd.setStatrtTime(statrtTime);
			reservationAdd.setEndTime(endTime);
			reservationAdd.setIsDisable("1");
			reservationAdd.setStatus("0");//已预约
			reservationAdd.setNowDate(format1.format(date));
			reservationAdd.setUserId(currentUser.getUserId().intValue());
			reservationAdd.setUserName(currentUser.getUserName());//当前登录的用户姓名
			reservationAdd.setUserPhone(currentUser.getPhonenumber());
			reservationAdd.setDrivingLicenseType(currentUser.getDrivingLicenseType());//驾照类型C1,C2
			reservationAdd.setSubject(currentUser.getSubject());//科目
			int resp = reservationService.insertReservation(reservationAdd);
			if(resp>0) {
				return AjaxResult.success("预约教练成功");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return AjaxResult.error();
	}

	/**
	 * 修改预约记录
	 */
	@GetMapping("/edit/{reservationId}")
	public String edit(@PathVariable("reservationId") Integer reservationId, ModelMap mmap)
	{
		
		Reservation reservation = reservationService.selectReservationById(reservationId);
		mmap.put("reservation", reservation);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改取消预约记录
	 * reservation.Status(0:已预约,1:已练车,2:已取消)
	 */
	@RequiresPermissions("system:reservation:edit")
	@Log(title = "预约记录", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Integer resid,Reservation reservation)
	{		
		if(reservation.getReservationId()==null) {
			reservation = reservationService.selectReservationById(resid);
		}
		//取消已预约的数据
		if("1".equals(reservation.getStatus())) {
			return AjaxResult.error("已经练过车了,不能取消哦!");
			
		}if("2".equals(reservation.getStatus())) {
			return AjaxResult.error("当前已是取消状态!");
			
		}else{
			reservation.setStatus("2");//修改为已取消
			reservation.setIsDisable("0");//修改为不可现
			reservation.setUpdateBy(ShiroUtils.getSysUser().getUserName());
			reservation.setUpdateTime(new Date());
		}
		return toAjax(reservationService.updateReservation(reservation));
	}
	
	//@RequiresPermissions("system:reservation:clickCancel")
	@Log(title = "预约教练页面-点击取消预约记录", businessType = BusinessType.UPDATE)
	@PostMapping("/clickCancel")
	@ResponseBody
	public AjaxResult clickCancel(String coachName,String coachPhone,String date,String timeValue,String phone)
	{		
		//教练预约页面不会显示（已预约），所以不会进来这里取消预约，phone取当前登录学员手机号
		phone = getSysUser().getPhonenumber();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timeValue = timeValue.replace("time", "");//时间几点
		String statrt_time = date+" "+timeValue+":00:00";
		Date statrttime = null;;
		try {
			statrttime = dateFormat.parse(statrt_time);//开始时间
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//开始时间
		
		Reservation reservation = new Reservation();
		reservation.setCoachName(coachName);//教练名
		reservation.setCoachPhone(coachPhone);//教练手机号
		reservation.setUserPhone(phone);//学员手机号
		reservation.setStatrtTime(statrttime);
		List<Reservation> reservationList = reservationService.selectReservationList(reservation);
		if(reservationList.size()>0) {
			if(reservationList.size()>1) {
				return error("取消失败，存在多条数据");
			}else if(reservationList.size()==1) {
				Reservation reservationUp = reservationList.get(0);//取出这条数据
				
				if("1".equals(reservationUp.getStatus())) {
					return AjaxResult.error("已经练过车了,不能取消哦!");
					
				}if("2".equals(reservationUp.getStatus())) {
					return AjaxResult.error("当前已是取消状态!");
					
				}else{
					reservationUp.setStatus("2");//修改为已取消
					reservationUp.setIsDisable("0");//修改为不可现
					reservationUp.setUpdateBy(ShiroUtils.getSysUser().getUserName());
					reservationUp.setUpdateTime(new Date());
				}
				return toAjax(reservationService.updateReservation(reservationUp));
			}
		}else {
			return error("取消预约失败");
		}
		return error("取消失败");
		//return toAjax(reservationService.updateReservation(reservation));
	}
	
	/**
	 * 删除预约记录
	 */
	@RequiresPermissions("system:reservation:remove")
	@Log(title = "预约记录", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(reservationService.deleteReservationByIds(ids));
	}
	
}
